<template>
    <el-card shadow="never" style="border: none; border: 1px solid red;width: 1150px;">
        <div class="search-container">
            <p class="textitem flex-start" style="font-size: 18px; margin-bottom: 16px;" placeholder="请输入关键字">
                机构管理
            </p>
            <el-form class="search-form" @submit.prevent>
                <el-row :gutter="0">
                    <el-col :span="18" class="no-padding">
                        <el-form-item @submit.prevent>
                            <el-input v-model="onsearchDate.searchValue" style=" width: 376px;height: 40px;"
                                size="large" placeholder="请输入关键字" :suffix-icon="Search"
                                @keyup.enter.prevent="onSearch" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="flex-end">
                        <el-button type="primary">新增机构</el-button>
                        <el-button>导出</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 表格顶部的操作栏 -->
        <div style="margin-bottom: var(--card-space);" v-if="$slots.toolbar">
            <slot name="toolbar"></slot>
        </div>

        <!-- 表格 -->
        <el-table :data="tableData.rows"
            :header-cell-style="{ background: '#ccddff', fontWeight: 'normal', color: '#515a6e', textAlign: 'center' }"
            style="font-size: 13px;">
            <el-table-column type="selection" width="55" />
            <!-- <el-table-column label="编号" prop="_id">
            </el-table-column> -->
            <el-table-column label="编号" prop="_id">
                <template #default="scope">
                    {{ scope.row._id ? scope.row._id.substring(0, 6) : '' }}
                </template>
            </el-table-column>

            <el-table-column label="机构图片" width="78">
                <!-- import.meta.env.VITE_BASE_URL -->
                <el-upload class="avatar-uploader" :action="`${baseURL}/image/upload`" :show-file-list="false"
                    name="file" :on-success="handleBgImageSuccess">
                    <!-- 当有图片时，渲染图片 -->
                    <img v-if="tableItem.image" :src="tableItem.image" class="avatar" />
                    <!-- 当没有图片，就显示图标 -->
                    <el-icon v-else class="avatar-uploader-icon">
                        <Picture></Picture>
                    </el-icon>
                </el-upload>
            </el-table-column>
            <el-table-column label="机构名称" prop="name" width="225" required />
            <el-table-column label="负责人姓名" prop="contacts" width="107" />
            <el-table-column label="电话" width="131">
                <template #default="scope">
                    {{ scope.row.phone ? scope.row.phone.slice(0, 3) + '****' + scope.row.phone.slice(7) : '' }}
                </template>
            </el-table-column>
            <el-table-column label="机构地址" prop="address" width="225" required />

            <el-table-column label="状态" width="80">
                <el-switch v-model="searchData.state" inline-prompt active-text="启动" inactive-text="禁止"
                    style="--el-switch-on-color: #13ce66;  --el-switch-disabled-color: #ccc;" />
            </el-table-column>
            <el-table-column label="操作" width="132">
                <!-- scope.row 获取到当前这一行的数据对象 -->
                <template #default="scope">
                    <!-- 点击事件：父组件调用子组件的方法，同时传值给子组件 -->
                    <el-button link type="primary">
                        修改
                    </el-button>
                    <el-button link style="color:#FA7468;" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <div v-if="pageData" class="flex-end" style="margin-top: 22px;">
            <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
                :total="tableData.total ?? 0" :page-sizes="[5, 10, 20, 40, 100]" background
                layout="total, sizes, prev, pager, next, jumper" />
        </div>
        <!-- // 在父组件中，通过 ref="permissionRef" 绑定子组件实例 -->
        <!-- <AddOrganization    ref="permissionRef" @findPermission="findPermission" /> -->

    </el-card>
</template>
<script setup lang="ts">

import { deleteOrganizationApi, findOrganizationsApi, OrganizationsType } from '@/api/organizationManage';
import { UploadProps } from 'element-plus';
import { Picture } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue';
const baseURL = import.meta.env.VITE_BASE_URL;
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
// import AddOrganization from './AddOrganization.vue';
// const permissionRef = useTemplateRef('permissionRef');

const tableData = reactive({
    rows: [], total: 0
})
const pageData = ref({
    currentPage: 1,
    pageSize: 10
});
const searchData = ref({ state: '' });
defineProps<{
    data: any[],
    columns: ColumnItem[],
    total?: number
}>();
const tableItem = ref<OrganizationsType>({
    _id: '', image: '', name: '', contacts: '', phone: '', address: '', intro: '', state: 1
});

// 图片上传后执行的方法
const handleBgImageSuccess: UploadProps['onSuccess'] = (
    res
) => {
    if (res.code == 200) {
        tableItem.value.image = res.data;
    }
}

//  查询机构管理数据的请求
onMounted(() => {
    findOrganization();
})
function findOrganization(_p0?: {
    /// <reference path="./__VLS_fake.d.ts" />
    value:
    /// <reference path="./__VLS_fake.d.ts" />
    string;
}) {
    findOrganizationsApi({
        page: pageData.value.currentPage,
        pageSize: pageData.value.pageSize,
        value: onsearchDate.value.searchValue
    })
        .then(res => {
            if (res.code == 200) {

                tableData.rows = res.data.rows;
                tableData.total = res.data.total;
            }
        })
}



//点击查询的按钮  双向绑定
const onsearchDate = ref({ searchValue: '' });
// 点击查询的点击事件   查询按钮发一次请求查询      findOrganization(params = {})里要传参--------------
function onSearch() {
    console.log("搜索的值", onsearchDate.value);
    findOrganization({
        value: onsearchDate.value.searchValue
    })
    console.log("1111", findOrganization);
}



// 点击删除事件
function handleDelete(row: OrganizationsType) {
    // 弹出确认框
    ElMessageBox.confirm(
        `机构信息删除后无法恢复，确定要删除吗？`,
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteOrganizationApi({ _id: row._id }).then(res => {
            if (res.code === 200) {
                tableData.rows = tableData.rows.filter(item => item._id !== row._id);
                ElMessage.success('删除成功');
            } else {
                ElMessage.error('删除失败');
            }
        }).catch(() => {
            ElMessage.error('删除失败，请重试');
        });
    })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}

</script>
<style scoped lang="scss">
.search-form .el-form-item {
    margin-bottom: 0 !important;
}

.no-padding {
    padding-left: 0 !important;
}

.flex-start {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.search-container {
    padding: 20px 0;
    background: #fff;
    border-radius: 4px;
}

.search-form {
    width: 100%;
}

.textitem {
    position: relative;
    padding-left: 12px;
    /* 给蓝色小条留出空间 */
}

.textitem::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 20px;
    background-color: rgba(41, 132, 248, 1);
    border-radius: 8px;
}

.avatar {
    width: 75px;
    height: 54px;
    display: block;
    /* 确保图片是块级元素 */
}

::placeholder {
    color: rgb(204, 204, 204);
}
</style>